def call() {
    // === 1. 自动注入 REFRESH_PARAMS 参数 ===
    def job = currentBuild.rawBuild.parent
    def defProp = job.getProperty(hudson.model.ParametersDefinitionProperty)
    def currentDefs = defProp?.parameterDefinitions ?: []

    // 如果还没有 REFRESH_PARAMS，就追加
    if (!currentDefs.any { it.name == 'REFRESH_PARAMS' }) {
        def newDefs = currentDefs + [
            booleanParam(
                name: 'REFRESH_PARAMS',
                defaultValue: false,
                description: '是否仅刷新参数定义'
            )
        ]
        properties([parameters(newDefs)])
        echo "[checkParams] 已为当前 Job 自动添加 REFRESH_PARAMS 参数"
    }

    // === 2. 如果本次只想刷新参数，直接退出 ===
    if (params.REFRESH_PARAMS) {
        currentBuild.description = "参数刷新模式"
        error "[checkParams] REFRESH_PARAMS=true，本次仅刷新参数定义，不做检测"
        return
    }

    // === 3. 获取缓存的参数名(UI界面展示的参数) ===
    def prevParamNames = params.keySet().findAll { it != 'REFRESH_PARAMS' } as Set
    // === 4. 获取当前 Jenkinsfile 的参数名 ===
    // def defProp = currentBuild.rawBuild.parent.getProperty(hudson.model.ParametersDefinitionProperty)
    def currentParamNames = defProp?.parameterDefinitions*.name?.findAll { it != 'REFRESH_PARAMS' } as Set ?: [] as Set


    echo "[checkParams] 上一次运行参数名: ${prevParamNames}"
    echo "[checkParams] 本次运行参数名: ${currentParamNames}"

    // === 5. 比较参数个数和名称 ===
    def added   = currentParamNames - prevParamNames
    def removed = prevParamNames - currentParamNames

    if (added || removed) {
        def problems = []
        if (added)   problems << "新增参数: ${added}"
        if (removed) problems << "删除参数: ${removed}"

        currentBuild.description = "参数有变更: ${problems.join(', ')}"
        error """
        检测到参数定义和上一次运行不一致:
        - 上一次运行参数: ${prevParamNames}
        - 本次运行参数:   ${currentParamNames}

        变更内容: ${problems.join('; ')}
        👉 本次构建中止，请确认参数是否需要刷新。
        """
    } else {
        echo "[checkParams] 参数名和数量与上一次一致。"
    }
}
